<?php
namespace Admin\Controller;
/**
 * 文章评论
 */
class CommentsController extends BaseController{

	/**
	 * 获取评论接口
	 */
	public function view(){
		if(IS_AJAX){
			$comments=M('comments')->where('article_id='.I('post.aid'))->order('create_time desc')->select();
			/*查询回复者昵称*/
	        foreach ($comments as $key => $comment) {
	            if($comment['to']!=0){
	            	$info=M('comments')->field('nickname,is_admin')->find($comment['to']);
	                $comments[$key]['replay']=$info['nickname'];
	                $comments[$key]['replay_admin']=$info['is_admin'];
	            }
	        }
			$this->ajaxReturn(array('status'=>1,'comments'=>$comments));
		}else{
			$this->error('访问错误');
		}
	}

	/**
	 * 删除评论
	 */
	public function deleteComment(){
		if(IS_AJAX){
			$sub=M('comments')->where('`to`='.I('post.id'))->find();
			if(!empty($sub)){
				//连同回复一块删除
				M('comments')->where('`to`='.I('post.id'))->delete();
			}
			if(M('comments')->delete(I('post.id'))){
                $this->ajaxReturn(array('status'=>1,'msg'=>'删除完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败'));
            }    
		}else{
			$this->error('访问错误');
		}
	}

	/**
	 * 回复评论
	 */
	public function replay(){
        if(IS_AJAX){
        	$data=array('to'=>I('post.id'),'comment'=>I('post.comment'),'article_id'=>I('post.article_id'));
        	$data['create_time']=time();
        	$data['browser']=getBrowser();
			$data['systemos']=getOs();
			$data['is_admin']=1;
			$data['nickname']=session('userinfo')[0]['username'];
            if(M('comments')->add($data)){
            	if(F('webSet')['Semail']==1){
	            	/*发邮件通知*/
	            	$toEmail=M('comments')->field('email')->find(I('post.id'))['email'];
	            	$toTitle=M('articles')->field('title')->find(I('post.article_id'))['title'];
	            	if(!empty($toEmail)){
	            		$msg="有人在".F('webSet')['webtitle']."中<a href='".U('/index/article/id/'.$data['article_id'].'@'.$_SERVER['SERVER_NAME'])."'>《".$toTitle."》文章</a>回复你:<p>{$data['comment']}</p>";
	            		$res=sendMail($toEmail,F('webSet')['webtitle'].'|系统回复',$msg);
	            		if($res!==true){
	            			$this->ajaxReturn(array('status'=>1,'msg'=>'回复完成，但是邮件发送失败：'.$res));
	            		}
	            	}
            	}
            	$this->ajaxReturn(array('status'=>1,'msg'=>'回复完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'回复失败'));
            }
        }else{
        	$this->error('访问错误');
        }
	}
}